﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;

namespace SystemCustomers
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!ReadFile()) return;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Manage());
        }

        
        private static bool ReadFile()
        {
            const string FILE_NAME = "MyFile.txt";

            if (!File.Exists(FILE_NAME))
            {
                MessageUtils.LogUtils.WriteToLog("{0} does not exist." + FILE_NAME);
                MessageUtils.LogUtils.SystemEventLogsInformation("{0} does not exist." + FILE_NAME);
                ErrorMessageBox(ReadFileError);
                return false;
            }
            Manage.ConnectionString = File.ReadAllText(FILE_NAME);
            MessageUtils.LogUtils.WriteToLog(Manage.ConnectionString);
            if (!CheckConnection()) return false;
            return true;
        }

        private static bool CheckConnection()
        {
             using (SqlConnection sqlC = new SqlConnection(Manage.ConnectionString))
             {
                 try
                 {
                     sqlC.Open();
                 }
                 catch (Exception Ex)
                 {
                     // Try to close the connection
                     if (sqlC != null)
                         sqlC.Dispose();
                     // Create a (useful) error message
                     string ErrorMessage = "A error occurred while trying to connect to the server.";
                     ErrorMessage += Ex.Message;
                     // Show error message (this = the parent Form object)
                     MessageUtils.LogUtils.SystemEventLogsInformation(ERRORMESSAGE);
                     MessageUtils.LogUtils.WriteToLog(ERRORMESSAGE);
                     ErrorMessageBox(ERRORMESSAGE);
                     // Stop here
                     return false;
                 }
                 sqlC.Close();
             }
            return true;
        }

        private const string ERRORMESSAGE = "Data Base Connection Error";
        private const string ReadFileError= "The File does not exist!!!!";

        private static void ErrorMessageBox(string errormessage)
        {
            MessageBox.Show(errormessage);
        }
    }
}
